package com.gigi.service.manual;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gigi.entity.CommentShiqinEntity;
import com.gigi.entity.FavoriteShiqinEntity;
import com.gigi.entity.LikeShiqinEntity;
import com.gigi.entity.UserShiqinEntity;
import com.gigi.enums.ErrorCodeEnum;
import com.gigi.enums.YesOrNoEnum;
import com.gigi.mapper.generated.UserShiqinMapper;
import com.gigi.model.*;
import com.gigi.service.generated.CommentShiqinService;
import com.gigi.service.generated.FavoriteShiqinService;
import com.gigi.service.generated.LikeShiqinService;
import com.gigi.service.generated.UserShiqinService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

@Service
public class UserManageService {

    private final UserShiqinService userService;
    private final UserShiqinMapper userMapper;
    private final FavoriteShiqinService favoriteShiqinService;
    private final LikeShiqinService likeShiqinService;
    private final CommentShiqinService commentShiqinService;

    /**
     * 密码加密盐值
     */
    private static final String SALT = "gigi";

    public UserManageService(UserShiqinService userService, UserShiqinMapper userMapper, FavoriteShiqinService favoriteShiqinService,
                             LikeShiqinService likeShiqinService, CommentShiqinService commentShiqinService) {
        this.userService = userService;
        this.userMapper = userMapper;
        this.favoriteShiqinService = favoriteShiqinService;
        this.likeShiqinService = likeShiqinService;
        this.commentShiqinService = commentShiqinService;
    }

    /**
     * 注册接口
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Response register(@RequestBody @Valid UserLoginRequest request) {
        if (StrUtil.isBlank(request.getName())) {
            return Response.buildFailure(ErrorCodeEnum.PARAM_ERROR.getErrCode(),
                    ErrorCodeEnum.PARAM_ERROR.getErrDesc());
        }

        // 手机号唯一性校验
        LambdaQueryWrapper<UserShiqinEntity> wrapper = new LambdaQueryWrapper<UserShiqinEntity>()
                .eq(UserShiqinEntity::getPhone, request.getPhone());
        if (userService.count(wrapper) > 0) {
            return Response.buildFailure(ErrorCodeEnum.ALREADY_REGISTER.getErrCode(),
                    ErrorCodeEnum.ALREADY_REGISTER.getErrDesc());
        }

        // 昵称唯一性校验
        LambdaQueryWrapper<UserShiqinEntity> wrapper1 = new LambdaQueryWrapper<UserShiqinEntity>()
                .eq(UserShiqinEntity::getName, request.getName());
        if (userService.count(wrapper1) > 0) {
            return Response.buildFailure(ErrorCodeEnum.NAME_REPEAT.getErrCode(),
                    ErrorCodeEnum.NAME_REPEAT.getErrDesc());
        }

        UserShiqinEntity entity = new UserShiqinEntity();
        entity.setPhone(request.getPhone());
        entity.setPassword(DigestUtils.md5DigestAsHex((request.getPwd() + SALT).getBytes()));
        entity.setName(request.getName());
        if (!userService.save(entity)) {
            return Response.buildFailure(ErrorCodeEnum.SAVE_FAILED.getErrCode(),
                    ErrorCodeEnum.SAVE_FAILED.getErrDesc());
        }

        // 创建默认收藏夹
        FavoriteShiqinEntity favoriteEntity = new FavoriteShiqinEntity();
        favoriteEntity.setName("我的收藏");
        favoriteEntity.setType(YesOrNoEnum.YES.getCode());
        favoriteEntity.setUserId(entity.getId());
        if (!favoriteShiqinService.save(favoriteEntity)) {
            return Response.buildFailure(ErrorCodeEnum.SAVE_FAILED.getErrCode(), ErrorCodeEnum.SAVE_FAILED.getErrDesc());
        }

        return Response.buildSuccess();
    }


    /**
     * 登录接口
     *
     * @param request
     * @return
     */
    public SingleResponse<Long> login(UserLoginRequest request) {
        LambdaQueryWrapper<UserShiqinEntity> wrapper = new LambdaQueryWrapper<UserShiqinEntity>()
                .eq(UserShiqinEntity::getPhone, request.getPhone())
                .eq(UserShiqinEntity::getPassword, DigestUtils.md5DigestAsHex((request.getPwd() + SALT).getBytes()));
        UserShiqinEntity entity = userService.getOne(wrapper, false);
        if (Objects.isNull(entity)) {
            return SingleResponse.buildFailure(ErrorCodeEnum.ACCOUNT_NOT_EXIST.getErrCode(),
                    ErrorCodeEnum.ACCOUNT_NOT_EXIST.getErrDesc());
        }
        return SingleResponse.of(entity.getId());
    }

    /**
     * 详情接口
     *
     * @param request
     * @return
     */
    public SingleResponse<UserDO> detail(IdRequest request) {
        UserShiqinEntity user = userService.getById(request.getId());
        if (Objects.isNull(user)) {
            return SingleResponse.buildFailure(ErrorCodeEnum.NO_DATA.getErrCode(),
                    ErrorCodeEnum.NO_DATA.getErrDesc());
        }
        UserDO userDO = new UserDO();
        userDO.setId(user.getId());
        userDO.setPic(user.getPic());
        userDO.setName(user.getName());
        userDO.setPhone(String.valueOf(user.getPhone()));
        userDO.setEmail(user.getEmail());
        userDO.setGender(user.getGender());
        userDO.setSign(user.getSign());
        userDO.setTagId(StrUtil.split(user.getTagId(), StrUtil.COMMA));
        if (Objects.nonNull(user.getBirth())) {
            String bir = user.getBirth().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
            userDO.setBirth(bir);
        }
        return SingleResponse.of(userDO);
    }

    /**
     * 编辑资料接口
     *
     * @param request
     * @return
     */
    public Response edit(UserDO request) {
        UserShiqinEntity entity = userMapper.selectById(request.getId());
        if (Objects.isNull(entity)) {
            return Response.buildFailure(ErrorCodeEnum.NO_DATA.getErrCode(), ErrorCodeEnum.NO_DATA.getErrDesc());
        }
        UserShiqinEntity target = new UserShiqinEntity();
        target.setId(entity.getId());
        target.setPic(request.getPic());
        target.setName(request.getName());
        target.setSign(request.getSign());
        target.setGender(request.getGender());
        target.setEmail(request.getEmail());
        target.setTagId(StrUtil.join(StrUtil.COMMA, request.getTagId()));
        if (StrUtil.isNotBlank(request.getBirth())) {
            LocalDate bir = LocalDate.parse(request.getBirth(), DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
            target.setBirth(bir);
        }
        boolean isSuccess = userService.updateById(target);
        if (!isSuccess) {
            return Response.buildFailure(ErrorCodeEnum.EDIT_FAILED.getErrCode(), ErrorCodeEnum.EDIT_FAILED.getErrDesc());
        }
        return Response.buildSuccess();
    }

    /**
     * 重置密码接口
     *
     * @param request
     * @return
     */
    public Response reset(ResetRequest request) {
        UserShiqinEntity entity = userService.getById(request.getId());
        if (Objects.isNull(entity)) {
            return Response.buildFailure(ErrorCodeEnum.NO_DATA.getErrCode(), ErrorCodeEnum.NO_DATA.getErrDesc());
        }
        if (!DigestUtils.md5DigestAsHex((request.getOldPwd() + SALT).getBytes()).equals(entity.getPassword())) {
            return Response.buildFailure(ErrorCodeEnum.ERROR_PWD.getErrCode(), ErrorCodeEnum.ERROR_PWD.getErrDesc());
        }
        UserShiqinEntity target = new UserShiqinEntity();
        target.setId(entity.getId());
        target.setPassword(DigestUtils.md5DigestAsHex((request.getNewPwd() + SALT).getBytes()));
        if (!userService.updateById(target)) {
            return Response.buildFailure(ErrorCodeEnum.EDIT_FAILED.getErrCode(), ErrorCodeEnum.EDIT_FAILED.getErrDesc());
        }
        return Response.buildSuccess();
    }

    /**
     * 卡片个数接口
     *
     * @param request
     * @return
     */
    public SingleResponse<CardDO> count(LikeDO request) {
        CardDO cardDO = new CardDO();
        LambdaQueryWrapper<LikeShiqinEntity> likeWrapper = new LambdaQueryWrapper<LikeShiqinEntity>()
                .eq(Objects.nonNull(request.getUserId()), LikeShiqinEntity::getUserId, request.getUserId());
        cardDO.setLikeCount(likeShiqinService.count(likeWrapper));
        LambdaQueryWrapper<CommentShiqinEntity> commentWrapper = new LambdaQueryWrapper<CommentShiqinEntity>()
                .eq(Objects.nonNull(request.getUserId()), CommentShiqinEntity::getUserId, request.getUserId());
        cardDO.setCommentCount((int) commentShiqinService.list(commentWrapper).stream().map(CommentShiqinEntity::getBlogId).distinct().count());
        return SingleResponse.of(cardDO);
    }

}
